package com.lzq.badminton.controller;

import com.lzq.badminton.Exception.SystemException;
import com.lzq.badminton.entity.User;
import com.lzq.badminton.enums.AppHttpCodeEnum;
import com.lzq.badminton.service.UserService;
import com.lzq.badminton.utils.SecurityUtils;
import com.lzq.community.domain.dto.AddPostDto;
import com.lzq.community.domain.vo.GetPostVo;
import com.lzq.community.domain.vo.Pager;
import com.lzq.community.domain.vo.ResponseResult;
import com.lzq.community.service.impl.DiscussPostService;
import com.lzq.community.util.CommunityConstant;
import com.lzq.community.domain.entity.*;
import com.lzq.community.event.EventProducer;
import com.lzq.community.service.impl.LikeService;
import com.lzq.community.util.CommunityUtil;
import com.lzq.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;


    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping(path = "/add")
    public ResponseResult addDiscussPost(AddPostDto addPostDto) {
        User user = userService.getById(SecurityUtils.getUserId());
        if (user == null) {
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(addPostDto.getTitle());
        post.setContent(addPostDto.getContent());
        post.setCreateTime(new Date());
        discussPostService.addDiscussPost(post);

        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(post.getId());
        eventProducer.fireEvent(event);

        // 计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, post.getId());

        // 报错的情况,将来统一处理.
        return ResponseResult.okResult();
    }

    @GetMapping(path = "/detail/{discussPostId}")
    public ResponseResult getDiscussPost(@PathVariable("discussPostId") Long discussPostId) {
        // 帖子

        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
        // 作者
        User user = userService.getById(post.getUserId());
        // 点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPostId);
        // 点赞状态
        int likeStatus = SecurityUtils.getUserId() == null ? 0 :
                likeService.findEntityLikeStatus(SecurityUtils.getUserId(), ENTITY_TYPE_POST, discussPostId);

        GetPostVo getPostVo = new GetPostVo();
        getPostVo.setDiscussPost(post);
        getPostVo.setLikeCount(likeCount);
        getPostVo.setLikeStatus(likeStatus);
        getPostVo.setUser(user);

        return ResponseResult.okResult(getPostVo);

    }

    // 置顶
    @PostMapping(path = "/top")
    public ResponseResult setTop(Long id) {
        discussPostService.updateType(id, 1);

        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(SecurityUtils.getUserId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        return ResponseResult.okResult();
    }

    // 加精
    @PostMapping(path = "/wonderful")
    public ResponseResult setWonderful(Long id) {
        discussPostService.updateStatus(id, 1);

        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(SecurityUtils.getUserId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        // 计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, id);

        return ResponseResult.okResult();
    }

    // 删除
    @PostMapping(path = "/delete")
    public ResponseResult setDelete(Long id) {
        discussPostService.updateStatus(id, 2);

        // 触发删帖事件
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(SecurityUtils.getUserId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        return ResponseResult.okResult();
    }

    @GetMapping(path = "getPostDetail")
    public ResponseResult getPostDetail(@RequestParam(name = "orderMode", defaultValue = "0") int orderMode, int pageSize, int pageNum){
        Pager<Map<String, Object>> page = new Pager<>();

        page.setTotal(discussPostService.findDiscussPostRows(0));

        List<DiscussPost> list = discussPostService
                .findDiscussPosts(0, page.getOffset(), page.getSize(), orderMode);
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", post);
                User user = userService.getById(post.getUserId());
                map.put("user", user);

                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);

                discussPosts.add(map);
            }
        }
        page.setData(discussPosts);
        return ResponseResult.okResult(page);
    }


}
